
import axios from "axios";
import { ElMessage } from "element-plus";
import router from 'route'


const TOKEN_INVALID = "token认证失败，请重新登录"
const NETWORT_ERROR = "网络发生错误，请稍后再试"
// 模拟的token
const token = 'sasfasjajkedasas'

const serve = axios.create({

    baseURL: 'https://api.github.com',
    // 超时的时长 8秒钟没有拿到数据，就会执行catch
    timeout: 8000
})

// 请求拦截  这个还可以用来做 进度条的加载
serve.interceptors.request.use((req => {
    const headers = req.headers
    if (!headers.Authorization) headers.Authorization = `Bearer${token}`
    return req
}), err => {
    return Promise.reject(err)
})

// 响应拦截
serve.interceptors.response.use(res => {
    const { data, code, msg } = res.data
    if (code === 200) {
        return data
    } else if (code === 40001) {
        ElMessage.error(TOKEN_INVALID)
        setTimeout(() => {
            router.push('/login')
        }, 1500)
        return Promise.reject(TOKEN_INVALID)
    } else {
        ElMessage.error(msg || NETWORT_ERROR)
        return Promise.reject(msg || NETWORT_ERROR)
    }
})

function request(options) {
    options.method = options.method || 'get'
    if(options.method.toLowerCase() === 'get') {
        options.params = options.data
    }
    if(process.env.NODE_ENV === 'production'){
        serve.defaults.baseURL = 'https://api.github.com'
      }else if(process.env.NODE_ENV === 'development'){
        serve.defaults.baseURL = 'https://api.github.com'
      }
    return serve(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach(item=>{
    request[item] = (url, data, options) => {
        console.log(url, data, options);
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})

export default request